export function patch(oldVnode, vnode) {
    const isRealElement = oldVnode.nodeType;
    if(isRealElement) {
        const oldElm = oldVnode;
        const parentNode = oldElm.parentNode;
        let el = createElm(vnode);
        parentNode.insertBefore(el, oldElm.nextSibling);
        parentNode.removeChild(oldElm);
        return el;
    }
}

function createElm(vnode) {
    let {tag, data, children, text} = vnode;
    if(typeof tag === 'string') {
        vnode.el = document.createElement(tag);
        updateProperties(vnode);
        children.forEach(child => {
            vnode.el.appendChild(createElm(child));
        })
    } else {
        vnode.el = document.createTextNode(text);
    }
    return vnode.el;
}

function updateProperties(vnode) {
    let newProps = vnode.data || {};
    let el = vnode.el;
    
    for(let key in newProps) {
        console.log(newProps[key]);
        if(key === 'style') {
            for(let styleName in newProps.style) {
                el.style[styleName] = newProps.style[styleName];
            }
        } else if(key === 'class') {
            el.className = newProps.class;
        } else {
            el.setAttribute(key, newProps[key]);
        }
    }
}